package com.jpxx.netty.helloAandB;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Client {  

	public static void main(String[] args) throws Exception {  
		// Configure the client.  
		EventLoopGroup group = new NioEventLoopGroup();  
		try {  
			Bootstrap b = new Bootstrap();  
			b.group(group)  
			.channel(NioSocketChannel.class)  
			.option(ChannelOption.TCP_NODELAY, true)  
			.handler(new ChannelInitializer<SocketChannel>() {  
				@Override  
				public void initChannel(SocketChannel ch) throws Exception {  
					ch.pipeline().addLast(new ClientHandler());  
				}  
			});  

			ChannelFuture future1 = b.connect("127.0.0.1",8765).sync(); //绑定8765服务端
			ChannelFuture future2 = b.connect("127.0.0.1",8764).sync(); //绑定8764服务端
			//Unpooled.copiedBuffer(res.getBytes())
			
			//分别用 future1和future2分发数据
			future1.channel().writeAndFlush(Unpooled.copiedBuffer("你好Netty服务器 ,我是连接'8765'发的数据11".getBytes())); 
			Thread.sleep(1000);
			future1.channel().writeAndFlush(Unpooled.copiedBuffer("你好Netty服务器 ,我是连接'8765'发的数据22".getBytes()));
			Thread.sleep(1000);
			future2.channel().writeAndFlush(Unpooled.copiedBuffer("你好Netty服务器 ,我是连接'8764'发的数据333".getBytes()));
			Thread.sleep(1000);
			future2.channel().writeAndFlush(Unpooled.copiedBuffer("你好Netty服务器 ,我是连接'8764'发的数据444".getBytes()));
			
			//短连接，发完就关闭
			//future.channel().writeAndFlush("你好Netty服务器 ,我是一个常见的客户端333").addListener(ChannelFutureListener.CLOSE);  
//			future.channel().write("1");
//			future.channel().write("2");
//			future.channel().flush();
			future1.channel().closeFuture().sync();  
			future2.channel().closeFuture().sync();  
		} finally {  
			group.shutdownGracefully();  
		}  
	}  

}  